/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Logger } from '..';

/**
 * Sendable合并性全局注册表
 *
 * 用于存储所有类的合并性分析结果，避免循环依赖和重复分析。
 *
 * 使用场景：
 * 1. 在 ClassAnalyzer 分析完所有类后，注册每个类的合并性
 * 2. 在 SendableMergeChecker.isSendableType() 中查询依赖类的合并性
 *
 * 生命周期：
 * - 每次代码生成开始前清空
 * - 分析阶段填充
 * - 生成阶段查询
 */
export class SendableMergeabilityRegistry {
  // 合并性映射：类名 -> 是否可合并
  private static mergeabilityMap = new Map<string, boolean>();

  /**
   * 注册类的合并性
   * @param className 类名
   * @param canMerge 是否可以合并
   */
  static register(className: string, canMerge: boolean): void {
    this.mergeabilityMap.set(className, canMerge);
    Logger.debug(`[SendableMergeabilityRegistry] 注册类合并性: ${className} -> ${canMerge}`);
  }

  /**
   * 查询类的合并性
   * @param className 类名
   * @returns 是否可合并，undefined 表示类还未分析
   */
  static canMerge(className: string): boolean | undefined {
    return this.mergeabilityMap.get(className);
  }

  /**
   * 检查类是否已注册
   * @param className 类名
   * @returns 是否已注册
   */
  static hasClass(className: string): boolean {
    return this.mergeabilityMap.has(className);
  }

  /**
   * 清空所有注册信息（每次代码生成前调用）
   */
  static clear(): void {
    const count = this.mergeabilityMap.size;
    this.mergeabilityMap.clear();
    Logger.debug(`[SendableMergeabilityRegistry] 清空注册表，已移除 ${count} 个类的合并性信息`);
  }
}
